<template>
  <div class="table-container">
    <el-table
      ref="table"
      :data="data"
      height="670"
      :onSelectionChange="handleSelection"
      border
      v-loading="loading"
      :element-loading-text="$t('lang.common.loading')"
      element-loading-background="rgba(255, 255, 255, 0.8)"
      style="width: 100%"
      @sort-change="sortChange"
      @row-click="clickRow"
      @select="onSelect"
      @select-all="onSelect"
      ><el-table-column type="selection" width="40" fixed="left" align="center" />
      <el-table-column label="序号" align="center" type="index" fixed="left" />
      <column-data
        v-for="column of columns"
        :key="column.label"
        :item="column"
        :options="options"
      />
      <el-table-column fixed="right" width="200" label="操作" align="center">
        <template #default="scope">
          <div class="operate">
            <slot :row="scope.row" name="operate" />
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div>
      <el-pagination
        class="pagination"
        :page-size="pagination.size"
        :page-sizes="pageSizes"
        background
        :current-page="pagination.current"
        layout="sizes, total, prev, pager, next, jumper"
        :onCurrentChange="currentChange"
        @size-change="handleSizeChange"
        :total="pagination.total"
        style="margin: 10px 0 0 0"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, PropType, watch, nextTick, computed } from 'vue'
import ColumnData from '@/components/TableWithPage/column-data.vue'
import { ObjectType } from 'typings/interfaces'
import { Optional } from 'typings/util'
import { intersectionBy, forEach, differenceBy } from 'lodash'
import { useStore } from 'vuex'

export interface Pagination {
  pageNum: number
  pageSize: number
  total: number
  orderType?: 'ASC' | 'DESC' // 排序方式
  orderBy?: string // 排序字段
}
interface Order {
  order: 'ascending' | 'descending' | null
  prop: string
}
export type DataSource = ObjectType[]

export default defineComponent({
  components: {
    ColumnData,
  },
  name: 'TableWithPage',
  props: {
    data: {
      type: Array,
    },
    columns: {
      type: Array,
    },
    Array,
    loading: {
      type: Boolean,
      default: false,
    },
    dataSource: {
      type: Array as PropType<DataSource>,
      required: true,
    },
    valuePath: {
      type: String,
      default: 'id',
    },
    needCheck: {
      type: Boolean,
      default: true,
    },
    selectedRows: {
      type: Array as PropType<ObjectType[]>,
      default: [],
    },
    pagination: {
      type: Object,
    },
    sort: {
      type: Function as PropType<(obj: Optional<Pagination>) => Promise<ObjectType[]>>,
      required: true,
    },
    options: {
      type: Object as PropType<ObjectType>,
      default: {},
    },
  },
  emits: ['pageChange', 'update:selectedRows', 'sizeChange'],
  // emits: {
  //   'pageChange': null,
  //   'update:selectedRows': null,
  // },
  setup(props, { emit }) {
    const store = useStore()
    const multipleSelection = ref('')
    const table = ref<ObjectType | null>(null)

    const toggleSelection = (selectedRows: ObjectType[], toggleStatus: boolean) =>
      forEach(selectedRows, (row) => table?.value?.toggleRowSelection(row, toggleStatus))

    const currentChange = (current: number) => {
      emit('pageChange', current)
    }
    const handleSizeChange = (current: number) => {
      
      store.commit('savePageSize', current)
      emit('sizeChange', current)
    }
    const handleSelection = (selection) => {
      multipleSelection.value = selection
    }
    /* 排序 */
    const sortChange = ({ order, prop }: Order) => {
      const types: Record<string, 'ASC' | 'DESC'> = {
        ascending: 'ASC',
        descending: 'DESC',
      }
      if (order && prop == 'statusName') {
        props.sort({ orderType: types[order], orderBy: 'status' })
      } else if (order) {
        props.sort({ orderType: types[order], orderBy: prop })
      }
    }
    // 监听数据发生变化 自动选择
    // watch(
    //   () => props.dataSource,
    //   () =>
    //     nextTick().then(() =>
    //       toggleSelection(
    //         intersectionBy(props.dataSource, props.selectedRows, props.valuePath),
    //         true
    //       )
    //     )
    // )

    // 选择项发生变化
    watch(
      () => props.selectedRows,
      () =>
        toggleSelection(differenceBy(props.dataSource, props.selectedRows, props.valuePath), false)
    )
    const pageSize = computed(() => store.state.global.pageSize)
    const pageSizes = computed(() => store.state.global.pageSizes)
    // 多选,选择行
    const onSelect = (rows: ObjectType[]) => {
      // const initRows = differenceBy(
      //   rows,
      //   intersectionBy(props.dataSource, rows, props.valuePath),
      //   props.valuePath
      // )
      emit('update:selectedRows', [...rows])
    }
    return {
      table,
      toggleSelection,
      sortChange,
      currentChange,
      handleSizeChange,
      handleSelection,
      multipleSelection,
      onSelect,
      pageSize,
      pageSizes,
      // clickRow: (row: ObjectType) => emit('update:selectedRows', [row]),
    }
  },
})
</script>
<style scoped lang="scss">
.table-container {
  margin: 10px 0 0 0;
  display: flex;
  flex-direction: column;
  height: 100%;
  flex: 1;
  :global(.el-pagination) {
    text-align: end;
  }
  .pagination {
    margin-top: auto;
  }
}
</style>
